import React, { useState } from 'react';
import styles from './index.less';
import { Button, Form, Input, Spin } from 'antd';
import { connect } from 'dva';
// components
import { TRMessage } from '@/components';
import { HttpCode } from '@/utils/contacts';
import { passwordReg } from '@/utils/regExp';
import { updatePassword } from '@/services/user';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 5 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 19 },
  },
};

const okCallback = (newPassWord, value, callback) => {
  if (newPassWord !== value) {
    return callback('您两次输入的密码不一致，请重新输入');
  }
  callback();
};

const getPwds = (newPassWord) => {
  return [
    { label: '原密码', key: 'oldPassWord' },
    {
      label: '新密码',
      key: 'newPassWord',
      rules: [
        {
          pattern: passwordReg,
          message: '您输入的密码不符合规则,密码长度为8-16位，大小写字母和数字组合',
        },
      ],
    },
    {
      label: '确认密码',
      key: 'okPassWord',
      rules: [
        {
          validator: (rule, value, callback) => {
            okCallback(newPassWord || '', value, callback);
          },
        },
      ],
    },
  ];
};

const ChangePasswordComp = (props) => {
  const passwordForm = React.createRef();
  const { currentUser, dispatch } = props;

  const [pwds, setPwds] = useState(getPwds(''));
  const [loading, setLoading] = useState(false);
  const [formDataLength, setFormDataLength] = useState(0);

  /* form改变触发函数 */
  const formValuesChange = (changedValues, allValues) => {
    const { getFieldsValue } = passwordForm.current;
    setFormDataLength(
      Object.keys(getFieldsValue() || {})
        .map((n) => getFieldsValue()[n])
        .filter((n) => n).length,
    );
    if (changedValues.newPassWord || changedValues.okPassWord) {
      setPwds(getPwds(allValues.newPassWord || ''));
    }
  };
  const handleSubmit = () => {
    passwordForm &&
      passwordForm.current.validateFields().then((values) => {
        changePassword({
          companynum: currentUser.companynum,
          newPassWord: values.newPassWord,
          oldPassWord: values.oldPassWord,
          userName: currentUser.mobile,
        });
      });
  };
  const changePassword = async (params) => {
    setLoading(true);
    const res = await updatePassword(params);
    setLoading(false);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      TRMessage.success('修改成功！');
      dispatch({ type: 'login/logout' });
    } else {
      TRMessage.error(res.message);
    }
  };

  return (
    <Spin spinning={loading}>
      <div className={styles.changePassword}>
        <div className={styles.header}>
          <div className={styles.title}>修改密码</div>
        </div>
        <Form ref={passwordForm} {...formItemLayout} onValuesChange={formValuesChange}>
          {pwds.map((item, index) => {
            return (
              <Form.Item
                name={item.key}
                label={item.label}
                key={index}
                rules={item.rules || []}
                validateTrigger={'onBlur'}
              >
                <Input.Password />
              </Form.Item>
            );
          })}
        </Form>
        <Button
          disabled={formDataLength !== pwds.length}
          type="primary"
          onClick={handleSubmit}
          className={styles.submitBtn}
        >
          提交
        </Button>
      </div>
    </Spin>
  );
};

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(ChangePasswordComp);
